package controller

import (
	"context"
	"encoding/json"
	"github.com/sirupsen/logrus"
	"my-desktop/common"
	"my-desktop/config"
	"my-desktop/models"
	"my-desktop/service"
	"my-desktop/utils"
	"net/http"
	"strconv"
	"time"
)

func Register(w http.ResponseWriter, r *http.Request) {
	params := common.GetRequestJsonParam(r)
	username := params["username"].(string)
	password := params["password"].(string)
	newPassword := utils.Md5Encode(password, "sys_user")
	//code := params["code"].(string)

	user := models.SysUser{}
	user.UserName = username
	user.Password = newPassword
	user.LoginIP = r.RemoteAddr

	data, err := service.Register(user)
	if data == nil {
		logrus.Warn("用户重复注册")
		common.Error(w, models.HasNoAuth, "用户重复注册", nil)
		return
	}
	if err != nil {
		logrus.Warn("用户注册SQL错误")
	}
}

func Login(w http.ResponseWriter, r *http.Request) {
	params := common.GetRequestJsonParam(r)
	username := params["username"].(string)
	password := params["password"].(string)
	newPassword := utils.Md5Encode(password, "sys_user")
	//code := params["code"].(string)

	user, err := service.Login(username, newPassword)
	token := utils.GetToken(user)
	if err != nil {
		logrus.Warn("用户登录SQL错误")
	}
	common.Success(w, models.Success, "登录成功", token)
}

func GetUserInfo(w http.ResponseWriter, r *http.Request) {
	// 检查token
	tokenString, err := common.GetToken(r, config.Http.Token)
	if err != nil {
		logrus.Warn("用户没有权限访问")
		common.Error(w, models.NotLogin, "用户没有权限访问", err)
		return
	}

	user, err := utils.ParseToken(tokenString)
	if err != nil {
		logrus.Warn("登录过期")
		common.Error(w, models.LoginExpired, "登录过期", err)
		return
	}

	// 查redis
	cacheUser, err := config.RDB.Get(context.Background(), "user:"+strconv.FormatUint(user.UserID, 10)).Result()
	if err == nil {
		var u models.UserVO
		json.Unmarshal([]byte(cacheUser), &u)
		common.Success(w, models.Success, "操作成功", u)
		return
	}

	// 查MySQL
	userVO, err := service.GetUserByUserID(user.UserID)
	if err != nil {
		logrus.Warn("获取用户信息失败")
		common.Error(w, models.NotFound, "获取用户信息失败", err)
		return
	}
	marshal, _ := json.Marshal(userVO)
	config.RDB.Set(context.Background(), "user:"+strconv.FormatUint(userVO.UserID, 10), marshal, time.Hour*2)
	common.Success(w, models.Success, "", userVO)
}

func Logout(w http.ResponseWriter, r *http.Request) {
	logrus.Info("用户退出登录")
}

func GOTest(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello golang"))
}
